package com.imflea.zero.service.meeting.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.imflea.zero.model.dao.meeting.MeetingShopUserMapper;
import com.imflea.zero.model.entity.meeting.MeetingShopUser;
import com.imflea.zero.model.entity.meeting.dto.MeetingShopUserDto;
import com.imflea.zero.model.entity.qx.QxRole;
import com.imflea.zero.model.entity.qx.vo.QxUserInfoVo;
import com.imflea.zero.service.meeting.IMeetingShopUserService;
import com.imflea.zero.service.qx.IQxUserInfoService;
import com.imflea.zero.util.base.CommonUtils;
import com.imflea.zero.utils.SessionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author xby
 * @since 2024-01-25
 */
@Service
public class MeetingShopUserServiceImpl extends ServiceImpl<MeetingShopUserMapper, MeetingShopUser> implements IMeetingShopUserService {
    @Autowired
    private IQxUserInfoService qxUserInfoService;

    @Override
    public MeetingShopUser saveOrUpdateMeetingShopUser(MeetingShopUser entity) {
        if (CommonUtils.isNull(entity.getId())) {
            entity.setId(CommonUtils.generateRandomString());
        }
        entity.setTenantId(SessionUtils.getTenantId());
        this.saveOrUpdate(entity);
        return entity;
    }

    @Override
    public List<MeetingShopUser> saveOrUpdateMeetingShopUserBatch(List<MeetingShopUser> meetingShopUsers) {
        for (MeetingShopUser mu : meetingShopUsers) {
            this.saveOrUpdateMeetingShopUser(mu);
        }
        return meetingShopUsers;
    }

    @Override
    public List<MeetingShopUser> queryByUserId(String userId) {
        String tenantId = SessionUtils.getTenantId();
        QueryWrapper<MeetingShopUser> queryWrapper = new QueryWrapper<>();
        if (!CommonUtils.isNull(tenantId)) {
            queryWrapper.eq("tenant_id", tenantId);
        }
        queryWrapper.eq("user_id", userId);
        List<MeetingShopUser> adoptInfos = this.list(queryWrapper);
        return adoptInfos;
    }

    @Override
    public List<String> queryShopIdsByUserId(String userId) {
        List<MeetingShopUser> shopUsers = this.queryByUserId(userId);
        List<String> shopIds = new ArrayList<>();
        if (!CommonUtils.isNull(shopUsers)) {
            shopIds = shopUsers.stream().map(item -> item.getMeetingShopId()).collect(Collectors.toList());
        }
        return shopIds;
    }

    @Override
    public PageInfo<MeetingShopUser> queryPage(MeetingShopUserDto dto) {
        Integer pageIndex = dto.getPageNum();
        Integer pageSize = dto.getPageSize();
        String tenantId = SessionUtils.getTenantId();
        QueryWrapper<MeetingShopUser> queryWrapper = new QueryWrapper<>();
        if (!CommonUtils.isNull(tenantId)) {
            queryWrapper.eq("tenant_id", tenantId);
        }
        PageHelper.startPage(pageIndex, pageSize);
        List<MeetingShopUser> adoptInfos = this.list(queryWrapper);
        PageInfo<MeetingShopUser> pageResult = new PageInfo<>(adoptInfos);
        return pageResult;
    }

    @Override
    public Map<String, List<QxUserInfoVo>> queryByShopId(String id) {
        Map<String, List<QxUserInfoVo>> result = new HashMap<>();
        String tenantId = SessionUtils.getTenantId();
        QueryWrapper<MeetingShopUser> queryWrapper = new QueryWrapper<>();
        if (!CommonUtils.isNull(tenantId)) {
            queryWrapper.eq("tenant_id", tenantId);
        }
        queryWrapper.eq("meeting_shop_id", id);
        List<MeetingShopUser> shopUsers = this.list(queryWrapper);
        List<QxUserInfoVo> allTenantUsers = qxUserInfoService.queryAllTenantUsers();

        String roleId = "oxmNzq0x";  //门店管理员
        List<QxUserInfoVo> empty = new ArrayList<>();
        List<QxUserInfoVo> allShopAdmins = new ArrayList<>();
        for (QxUserInfoVo vo : allTenantUsers) {
            List<QxRole> roleList = vo.getRoleList();
            if (!CommonUtils.isNull(roleList)) {
                for (QxRole role : roleList) {
                    if (roleId.equals(role.getId())) {
                        allShopAdmins.add(vo);
                        break;
                    }
                }
            }
        }
        if (CommonUtils.isNull(allShopAdmins)) {
            result.put("existed", empty);
            result.put("notExist", empty);
        } else {
            if (!CommonUtils.isNull(shopUsers)) {
                Set<MeetingShopUser> distinct = shopUsers.stream().collect(Collectors.toSet());
                final Set<String> existedUserIds = shopUsers.stream().map(item -> item.getUserId()).collect(Collectors.toSet());
                final Map<String, String> map = distinct.stream().collect(Collectors.toMap(MeetingShopUser::getUserId, p -> p.getId()));
                if (!CommonUtils.isNull(existedUserIds)) {
                    List<QxUserInfoVo> existedUsers = allShopAdmins.stream().filter(item -> (existedUserIds.contains(item.getId()))).collect(Collectors.toList());
                    existedUsers.forEach(item -> item.setRelationId(map.get(item.getId())));
                    List<QxUserInfoVo> notExistedUsers = allShopAdmins.stream().filter(item -> (!existedUserIds.contains(item.getId()))).collect(Collectors.toList());
                    result.put("existed", existedUsers);
                    result.put("notExist", notExistedUsers);
                } else {
                    result.put("existed", empty);
                    result.put("notExist", allShopAdmins);
                }
            } else {
                result.put("existed", empty);
                result.put("notExist", allShopAdmins);
            }

        }
        return result;
    }


}
